<template>
  <div>
<!--    // 面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<!--    //卡片视图区域 -->
    <el-card>
<!--      // 搜素与添加-->
      <el-row :gutter="10">
        <el-col :span="8" class="search">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" @clear="getUsersList" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialog = true">添加用户</el-button>
        </el-col>
      </el-row>
<!--      // 用户列表-->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUsers(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="rightOpen(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
<!--    // 添加用户对话框-->
    <el-dialog title="添加用户" :visible.sync="addDialog"
      width="50%" @close="addDialogClose">
<!--      // 内容主题区-->
      <el-form :model="addForm" :rules="addRules" ref="addRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
<!--      // 底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
<!--    // 修改用户对话框-->
    <el-dialog title="修改用户信息" :visible.sync="editDialog" width="50%" @close="editClose">
      <el-form :model="editUser" :rules="addRules" ref="editRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editHandle(editUser.id)">确 定</el-button>
      </span>
    </el-dialog>
<!--    // 分配权限对话框-->
    <el-dialog @close="rightClose" title="提示" :visible.sync="rightVisible" width="50%">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>
          分配新角色：
          <template>
            <el-select v-model="role" placeholder="请选择">
              <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </template>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="rightVisible = false">取 消</el-button>
    <el-button type="primary" @click="rightHandle">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证邮箱规则
    var checkEmail = (rules, value, callback) => {
      // 验证邮箱格式的正则表达式
      const regMaile = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regMaile.test(value)) {
        return callback()
      }
      return callback(new Error('邮箱格式错误'))
    }
    // 验证手机规则
    var checkMobile = (rules, value, callback) => {
      // 验证手机的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback()
      }
      return callback(new Error('手机格式错误'))
    }
    return {
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示数据条数
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制添加对话框的显示与隐藏
      addDialog: false,
      // 控制修改对话框的显示与隐藏
      editDialog: false,
      // 添加用户框 数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户信息规则
      addRules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }, { min: 3, max: 10, message: '用户名字符必须在3-10之间', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }, { min: 3, max: 10, message: '密码字符必须在3-10之间', trigger: 'blur' }],
        email: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }, { validator: checkEmail, trigger: 'blur' }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }]
      },
      // 查到的用户修改对象
      editUser: {},
      // 分配权限对框框显示与隐藏布尔值
      rightVisible: false,
      // 学要被分配角色的用户信息
      userInfo: {},
      // 已选中的角色
      role: '',
      // 角色数据
      roles: []
    }
  },
  // 初始化用户列表
  created() {
    this.getUsersList()
  },
  methods: {
    async getUsersList() {
      const { data: result } = await this.$http.get('users', { params: this.queryInfo })
      if (result.meta.status !== 200) return console.log('用户获取失败')
      this.userList = result.data.users
      this.total = result.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newNumber) {
      this.queryInfo.pagenum = newNumber
      this.getUsersList()
    },
    // 角色状态修改
    async userChanged(obj) {
      const { data: result } = await this.$http.put(`users/${obj.id}/state/${obj.mg_state}`)
      console.log(result)
      if (result.meta.status !== 200) return this.$message.error('修改状态失败')
      this.$message.success('更新用户状态成功！')
    },
    // 添加用户
    addUser() {
      this.$refs.addRef.validate(async valid => {
        if (!valid) return
        // 添加用户请求
        const { data: result } = await this.$http.post('users', this.addForm)
        if (result.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        this.addDialog = false
        this.getUsersList()
      })
    },
    // 重置添加用户信息
    addDialogClose() {
      this.$refs.addRef.resetFields()
    },
    // 修改用户操作
    async showEditDialog(id) {
      const { data: result } = await this.$http.get('users/' + id)
      console.log(result)
      if (result.meta.status !== 200) {
        this.$message.error('获取修改用户失败')
        return
      }
      this.editUser = result.data
      this.$message.success('获取修改用户成功')
      this.editDialog = !this.editDialog
      // console.log(id)
    },
    // 提交修改用户信息
    editHandle(id) {
      this.$refs.editRef.validate(async valid => {
        const { data: result } = await this.$http.put('users/' + id, this.editUser)
        if (result.meta.status !== 200) {
          this.$message.error('修改失败')
          return
        }
        this.$message.success('修改成功')
        this.editDialog = !this.editDialog
        this.getUsersList()
      })
    },
    // 重置修改用户信息
    editClose() {
      this.$refs.editRef.resetFields()
    },
    // 删除用户信息
    deleteUsers(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: result } = await this.$http.delete('users/' + id)
        if (result.meta.status !== 200) {
          this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getUsersList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 显示与隐藏权限对话框的函数
    async rightOpen(userInfo) {
      this.userInfo = userInfo

      // 在展示对话框之前，获取所有角色的列表
      const { data: result } = await this.$http.get('roles')
      if (result.meta.status !== 200) return this.$message.error('获取角色权限失败')
      console.log(result.data)
      this.roles = result.data
      this.rightVisible = true
    },
    // 角色修改
    async rightHandle() {
      if (!this.role) return this.$message.error('请选择分配角色')
      const { data: result } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.role })
      if (result.meta.status !== 200) return this.$message.error('更新用户角色失败')

      this.$message.success('更新用户角色成功')
      this.getUsersList()
      this.rightVisible = false
    },
    // 分配权限对话框关闭时执行下面函数
    rightClose() {
      this.userInfo = {}
      this.role = ''
    }
  }
}
</script>

<style scoped>
.el-table {
  margin-bottom: 10px;
}
</style>
